package com.aaa.project.controller;

import com.aaa.entity.AlipayBean;
import com.aaa.entity.GGoods;
import com.aaa.entity.OOrder;
import com.aaa.entity.Order;
import com.aaa.project.service.IGGoodsService;
import com.aaa.project.service.IOOrderService;
import com.aaa.project.service.PayService;
import com.aaa.util.Result;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@SuppressWarnings("all")
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private IGGoodsService igGoodsService;
    @Autowired
    private IOOrderService orderService;

    @PostMapping(value="cart/alipay1")
    public Result cartAlpay(@RequestBody AlipayBean alipayBean) throws Exception {
        System.out.println("cartalpay=================================="+alipayBean);
        //        System.out.println(alipayBean);
//        GGoods gGoods = igGoodsService.find(alipayBean.getCode());
//        System.out.println("gGoods = " + gGoods);
//        String code = alipayBean.getCode();
//        String price = alipayBean.getPrice();
//        String gname = gGoods.getGname();
        AlipayTradePrecreateResponse response =alPay(alipayBean);
        UpdateWrapper<OOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("code",alipayBean.getCode()).set("state", 1);
        orderService.update(null, updateWrapper);

        Map map = new HashMap<>();
        if (ResponseChecker.success(response)) {
            String qrCode = response.getQrCode();
            map.put("codeUrl", qrCode);  //生成的二维码链接，不可直接打开，后面会说到
            map.put("price", alipayBean.getPrice());
//            map.put("orderId", orderId); //生成的订单号应该要返回给前端
//            integer = orderService.insertOrder(order); //插入订单数据库

        } else {
            //integer = 0;
            map.put("codeUrl", "");
            map.put("price", "");
        }
        System.out.println("map====================================="+map);
        return new Result(map);
    }

    @PostMapping(value = "order/alipay1")
    public Result orderAlPay(@ModelAttribute AlipayBean alipayBean) throws Exception {
        System.out.println("orderalp=================="+alipayBean);
//        GGoods gGoods = igGoodsService.find(alipayBean.getCode());
//        System.out.println("gGoods = " + gGoods);
//        String code = alipayBean.getCode();
//        String price = alipayBean.getPrice();
//        String gname = gGoods.getGname();
        AlipayTradePrecreateResponse response =alPay(alipayBean);

        Map map = new HashMap<>();
        if (ResponseChecker.success(response)) {
            String qrCode = response.getQrCode();
            map.put("codeUrl", qrCode);  //生成的二维码链接，不可直接打开，后面会说到
            map.put("price", alipayBean.getPrice());
//            map.put("orderId", orderId); //生成的订单号应该要返回给前端
//            integer = orderService.insertOrder(order); //插入订单数据库
        } else {
            //integer = 0;
            map.put("codeUrl", "");
            map.put("price", "");
        }
        System.out.println("map======================"+map);
        return new Result(map);
    }
//    @PostMapping(value = "cart/alipay1")
//    public Result cartAlPay(){
//
//    }
//    @PostMapping("cart/alipay1")
//    public Result cartAlPay(@ModelAttribute AlipayBean alipayBean) throws Exception {
//        AlipayTradePrecreateResponse response=alPay(alipayBean)
//    }


    @GetMapping("order/paystatus/{code}")
    public Result payStatus(@PathVariable String code){
        QueryWrapper<OOrder> queryWrapper = new QueryWrapper<OOrder>();
        queryWrapper.eq("code",code);
        System.out.println("code=========================================="+code);
        List<OOrder> one = orderService.list(queryWrapper);
        Result<Object> result = new Result();
        System.out.println("订单======================================================================================"+one.get(0));
        if(one.get(0).getState().equals(0)){

            return result;
        }
        result.setCode(400);
        return result;

    }
    @RequestMapping("/notify")  // 注意这里必须是POST接口
    public String notifyAsync(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            map.put(key, value);
        }
        //验签
        try {
            if (Factory.Payment.Common().verifyNotify(map)) {
                //验证用户的支付结果
                String trade_status = request.getParameter("trade_status");
                if ("TRADE_SUCCESS".equals(trade_status)) {
                    //这里可以更新订单的状态等等。。
                    System.out.println("dsadssadads");
                    System.out.println(map.get("out_trade_no"));
                  orderService.updateOOrder(map.get("out_trade_no"));
                }
            } else {
                return "fail";
            }
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }

    @ApiOperation(value = "生成二维码")
    @PostMapping("/order/getNativeCodeUrl/{code}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "order")
    })
    public Result getNativeCodeUrl(@PathVariable String code) {
        Order order = new Order();
        order.setOrderNum(code);
        order.setMoney("0.001");
        order.setDescribe("我真tm帥");
        Map map = payService.getNativeByOrder(order);
        map.put("code", code);
        map.put("price", 66666666);
        System.out.println("map=========================================" + map);
        return new Result(map);
    }

    @GetMapping("payForOrder/{code}")
    @ApiOperation(value = "根据订单的编号获取订单的状态")
    public Result getPayStatus(@PathVariable("code") String orderNum) {
        Map<String, String> map = payService.getPayStatus(orderNum);
        Result result = new Result();
        result.setCode(200);
        result.setMsg("支付中");
        result.setT(map);
        return result;
    }
    private AlipayTradePrecreateResponse alPay(AlipayBean alipayBean) throws Exception {
        System.out.println(alipayBean);
        GGoods gGoods = null;
        System.out.println("gGoods = " + gGoods);
        String code = alipayBean.getCode();
        String price = alipayBean.getPrice();
        String gname=null;
        try{
            gGoods = igGoodsService.find(alipayBean.getCode());
            gname = gGoods.getGname();
        }catch (Exception e){

        }
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(gname, code, price);
        return  response;
    }

}
